import { request, } from "../../request/index.js";
import { getOpenid, showToast } from "../../utils/asyncWx.js";
//引入事先写好的日期设置util.js文件
var datePicker = require('../../utils/dateSetting.js')

//设定当前的时间，将其设定为常量
const date = new Date();
const year = date.getFullYear();
const month = date.getMonth() + 1;


Page({

  /**
   * 页面的初始数据
   */
  data: {
    title: "",
    brief: "",
    deadline: "", // 存放时间戳格式的截止时间
    time: "",     // 存放格式化的截止时间
    multiArray: [],
    multiIndex: [0, 0, 0, 0, 0],
    choose_year: "",
    beacon:{},
    // beacon: {
    //   accuracy: 156.37464111346165,
    //   major: 7750,
    //   minor: 9727,
    //   proximity: 0,
    //   rssi: -67,
    //   uuid: "fda50693-a4e2-4fb1-afcf-c6eb07647825"
    // },
    eventid: ""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      multiArray:
        [
          [year + "年", year + 1 + "年", year + 2 + "年"],
          datePicker.determineMonth(),
          datePicker.determineDay(year, month),
          datePicker.determineHour(),
          datePicker.determineMinute()
        ],
    })
    wx.showShareMenu({
      withShareTicket: true //要求小程序返回分享目标信息
    })
  },

  //----调试----
  onShow() {
    console.log(this.data.beacon)
  },
  //----调试----


  //最后呈现时间的函数。
  bindMultiPickerChange: function (e) {
    let fullYear = this.data.multiArray[0][this.data.multiIndex[0]].slice(0, -1)
    let month = this.fillZero(this.data.multiArray[1][this.data.multiIndex[1]].slice(0, -1))
    let day = this.fillZero(this.data.multiArray[2][this.data.multiIndex[2]].slice(0, -1))
    let hour = this.fillZero(this.data.multiArray[3][this.data.multiIndex[3]].slice(0, -1))
    let minute = this.fillZero(this.data.multiArray[4][this.data.multiIndex[4]].slice(0, -1))
    let second = "00"
    var dateStr = this.data.multiArray[0][this.data.multiIndex[0]] +
      this.data.multiArray[1][this.data.multiIndex[1]] +
      this.data.multiArray[2][this.data.multiIndex[2]] +
      this.data.multiArray[3][this.data.multiIndex[3]] +
      this.data.multiArray[4][this.data.multiIndex[4]];
    var date = new Date(fullYear, month - 1, day, hour, minute, second);
    console.log("date:", date);
    console.log("date.getTime():", date.getTime().toString().slice(0, -3));
    this.setData({
      time: dateStr,
      deadline: date.getTime().toString()
    })
  },
  // 当时间选择器呈现并进行滚动选择时间时调用该函数。
  bindMultiPickerColumnChange: function (e) {
    //e.detail.column记录哪一行发生改变，e.detail.value记录改变的值（相当于multiIndex）
    switch (e.detail.column) {
      //这里case的值有0/1/2/3/4,但除了需要记录年和月来确定具体的天数外，其他的都可以暂不在switch中处理。
      case 0:
        //记录改变的年的值
        let year = this.data.multiArray[0][e.detail.value];
        this.setData({
          choose_year: year.substring(0, year.length - 1)
        })
        break;
      case 1:
        //根据选择的年与月，确定天数，并改变multiArray中天的具体值
        let month = this.data.multiArray[1][e.detail.value];
        let dayDates = datePicker.determineDay(this.data.choose_year, month.substring(0, month.length - 1));
        //这里需要额外注意，改变page中设定的data，且只要改变data中某一个值，可以采用下面这种方法
        this.setData({
          ['multiArray[2]']: dayDates
        })
        break;
    }
    //同上，上面改变的是二维数组中的某一个一维数组，这个是改变一个一维数组中某一个值，可供参考。
    this.setData({
      ["multiIndex[" + e.detail.column + "]"]: e.detail.value
    })
  },
  // 
  async createEvent() {
    if (this.data.title.length > 0 &&
      this.data.deadline.length > 0 &&
      this.data.beacon != null) {
      await this.createAndShare();
    } else {
      await showToast({
        title: '请先补全事件相关信息'
      })
    }
  },

  // 创建打卡事件
  async createAndShare() {
    // 封装请求参数
    // let openid = wx.getStorageSync('openid')  // 获取openid
    let data = {
      title: this.data.title,
      brief: this.data.brief,
      deadline: this.data.deadline,
      beacon: this.data.beacon,
      // beacon: this.data.beacon,
      // openid
    }
    // 封装请求头
    let header = { "Content-Type": "application/json" }

    // 创建打卡事件,同时后台也会将考勤者添加到打卡事件中，并设置为考勤者身份
    const res = await request({ url: "/AttendanceEvent/createEvent", method: "POST", data: JSON.stringify(data), header })
    console.log("createEvent: ", res)
    if (res.data.data == null) {
      await showToast({ title: res.data.msg })
      console.log("res.data.data==null    showToast")
      return
    }

    // 保存eventid
    let eventid = res.data.data
    this.setData({ eventid })
    console.log("eventid: ", eventid)
  },

  // 处理title输入事件
  handleTitleInput(e) {
    const { value } = e.detail
    this.setData({
      title: value
    })
  },
  handleBriefInput(e) {
    const { value } = e.detail
    this.setData({
      brief: value
    })
  },
  // 时间转对象
  strToDate(dateStr) {
    let fullYear = parseInt(dateStr.substring(0, 4));
    let month = parseInt(dateStr.substring(5, 7).substring(0, 1) == '0' ? dateStr.substring(6, 7) : dateStr.substring(5, 7))
    let day = parseInt(dateStr.substring(8, 10).substring(0, 1) == '0' ? dateStr.substring(9, 10) : dateStr.substring(8, 10))
    let hour = parseInt(dateStr.substring(11, 13).substring(0, 1) == '0' ? dateStr.substring(12, 13) : dateStr.substring(11, 13))
    let minute = parseInt(dateStr.substring(14, 16).substring(0, 1) == '0' ? dateStr.substring(15, 16) : dateStr.substring(14, 16))
    let second = parseInt(dateStr.substring(17, 19).substring(0, 1) == '0' ? dateStr.substring(18, 19) : dateStr.substring(17, 19))
    return new Date(fullYear, month - 1, day, hour, minute, second);
  },
  // 位数不够，补零
  fillZero(numStr) {
    if (numStr.length < 2) {
      numStr = "0" + numStr
    }
    return numStr
  },

  /**
 * 用户点击button分享
 */
  onShareAppMessage(res) {
    // console.log("onShareAppMessage",res);
    // let { eventid } = res.target.dataset.info;
    let {eventid} = this.data

    return {
      title: '分享打卡事件',
      path: '/pages/find_event/find_event?eventid=' + eventid,
      // path: '/pages/find_event/find_event',
      imageUrl: 'https://pic.imgdb.cn/item/60742ebb8322e6675cb3b97f.jpg',
      success: function (res) {
        console.log("success:", res);
        let shareTicket = res.shareTickets[0];
        console.log(shareTicket);
        // 转发成功
        wx.showToast({
          title: "分享成功",
          icon: 'success',
          duration: 2000
        })
      },
      fail: function (res) {
        console.log("fail:", res)
        // 分享失败
      }
    }
  }
})